package com.sheledon.flyCat.network.socket.server;

import com.sheledon.flyCat.core.handler.DispatcherHandler;
import com.sheledon.flyCat.network.socket.http.HttpRequest;
import com.sheledon.flyCat.network.socket.http.HttpResponse;
import com.sheledon.flyCat.network.socket.resolver.HttpResolver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author sheledon
 */
public class HttpServerHandler implements Runnable{
    private Socket socket ;

    public HttpServerHandler(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        try(OutputStream opt = socket.getOutputStream();
            InputStream inp = socket.getInputStream()) {
            //parse http请求
            HttpRequest request = HttpResolver.resolve(inp);
            //调用相应的方法处理
            HttpResponse response = DispatcherHandler.dispatch(request);
            opt.write(response.transferResponse().getBytes(StandardCharsets.UTF_8));
            opt.flush();
            socket.shutdownOutput();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
